package com.cxx.home.service.impl;


import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cxx.common.dto.SessionDto;
import com.cxx.common.dto.UserDto;
import com.cxx.common.entity.Account;
import com.cxx.common.entity.User;
import com.cxx.common.mapper.AccountMapper;
import com.cxx.common.mapper.UserMapper;
import com.cxx.framework.web.CustomException;
import com.cxx.home.service.SessionService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


@Service
public class SessionServiceImpl implements SessionService {
    @Resource
    private AccountMapper accountMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public SessionDto create(String name, String password) {
        LambdaQueryWrapper<Account> queryWrapper = Wrappers.lambdaQuery(Account.class).eq(Account::getAccountName, name);
        Account account = accountMapper.selectOne(queryWrapper);
        if (account == null) {
            throw new CustomException("账户: " + name + " 不存在");
        }

        if (!BCrypt.checkpw(password, account.getPassword())) {
            throw new CustomException("密码不正确");
        }

        User user = userMapper.selectById(account.getUserId());
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);
        userDto.setAccountId(account.getId());
        userDto.setAccountName(name);

        SessionDto sessionDto = new SessionDto();
        StpUtil.login(account.getId());
        sessionDto.setSaToken(StpUtil.getTokenInfo());
        sessionDto.setUserInfo(userDto);

        StpUtil.getSession().set("username", name);

        return sessionDto;
    }
}
